package com.hzw.saas.common.config.util;

import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * TokenExtractor that strips the authenticator from a bearer token request (with an Authorization header in the form "Bearer <TOKEN>", or as a request parameter if that fails). The access token is the principal in the authentication token that is extracted.
 * @Date 2021/6/25 2:36 下午
 * @Created by sonam
 */
@Slf4j
@Component
public class BearerTokenExtractor {
    private final static String BEARER_TYPE = "Bearer";
    public final static String ACCESS_TOKEN = "access_token";

    public String extract(HttpServletRequest request) {
        return extractHeaderToken(request);
    }

    /**
     * Extract the OAuth bearer token from a header.
     *
     * @param request The request.
     * @return The token, or null if no OAuth authorization header was supplied.
     */
    protected String extractHeaderToken(HttpServletRequest request) {
        Enumeration<String> headers = request.getHeaders("Authorization");
        while (headers.hasMoreElements()) { // typically there is only one (most servers enforce that)
            String value = headers.nextElement();
            if ((value.toLowerCase().startsWith(BEARER_TYPE.toLowerCase()))) {
                String authHeaderValue = value.substring(BEARER_TYPE.length()).trim();
                int commaIndex = authHeaderValue.indexOf(',');
                if (commaIndex > 0) {
                    authHeaderValue = authHeaderValue.substring(0, commaIndex);
                }
                return authHeaderValue;
            }
        }

        log.debug("Token not found in headers. Trying request parameters.");
        String token = request.getParameter(ACCESS_TOKEN);
        if (token == null) {
            log.debug("Token not found in request parameters.  Not an OAuth2 request.");
        }

        return token;
    }
}
